-- Copyright (c) 2025 Huawei Technologies Co., Ltd.
-- openUBMC is licensed under Mulan PSL v2.
-- You can use this software according to the terms and conditions of the Mulan PSL v2.
-- You may obtain a copy of Mulan PSL v2 at: http://license.coscl.org.cn/MulanPSL2
-- THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
-- EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
-- MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
-- See the Mulan PSL v2 for more details.

local m = {}

local base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"

function m.base64_encode(input)
    local output = ""
    local i = 1
    local len = #input


    local b1, b2, b3, c1, c2, c3, c4
    while i <= len do
        b1 = string.byte(input, i) or 0     -- 取当前字节
        b2 = string.byte(input, i + 1) or 0 -- 取后1个字节
        b3 = string.byte(input, i + 2) or 0 -- 取后2个字节

        -- 将3个字节区分为4个6位的块
        c1 = b1 >> 2                         -- b1右移2位，取高6位
        c2 = ((b1 & 0x03) << 4) | (b2 >> 4)  -- b1取低2位并左移4位，b2右移4位取高4位
        c3 = ((b2 & 0x0f) << 2) | (b3 >> 6)  -- b2取低4位并左移2位，b3右移6位取高2位
        c4 = b3 & 0x3f                       -- b3取低6位

        output = output .. base64_chars:sub(c1 + 1, c1 + 1)
        output = output .. base64_chars:sub(c2 + 1, c2 + 1)

        if i + 1 <= len then -- 若余1字节，需要补1个"="
            output = output .. base64_chars:sub(c3 + 1, c3 + 1)
        else
            output = output .. "="
        end

        if i + 2 <= len then -- 若余2字节，需要再补1个"="
            output = output .. base64_chars:sub(c4 + 1, c4 + 1)
        else
            output = output .. "="
        end

        i = i + 3 -- 每次操作3字节
    end
    return output
end

function m.hex_to_bytes(hex_str)
    local bytes = ""
    local byte
    for i = 1, #hex_str, 2 do                      -- 步进2位
        byte = tonumber(hex_str:sub(i, i + 1), 16) -- 转换位16进制
        bytes = bytes .. string.char(byte)
    end
    return bytes
end

return m